package zookeeper

import (
	"gitee.com/dennis-kk/service-box-go/util/slog"
	"github.com/go-zookeeper/zk"
	"strings"
	"sync/atomic"
)

// tools func to rewrite zookeeper client

type zkLogHelper struct {
	open   uint32
	logger slog.BoxLogger
}

func makeZkLogHelper(state uint32) *zkLogHelper {

	opts := []slog.Option{
		slog.WithCallerSkipCount(1),
		slog.WithAppName("zookeeper"),
	}

	return &zkLogHelper{
		open:   state,
		logger: slog.Children(opts...),
	}
}

func (zl *zkLogHelper) Printf(format string, args ...interface{}) {
	if zl == nil || atomic.LoadUint32(&zl.open) == 0 {
		return
	}

	if zl.logger != nil {
		zl.logger.Info("[zookeeper] "+format, args...)
	}
}

//zkEventHanler zookeeper event call back handler!
//called by zookeeper recvLoop goroutine
func zkEventHanler(event zk.Event) {

}

func isZKConnValid(conn *zk.Conn) bool {
	if conn == nil {
		return false
	}
	return conn.State() == zk.StateConnected || conn.State() == zk.StateHasSession
}

//preProcessSvsPath 预处理服务路径，所有路径处理为
func preProcessSvsPath(prefix string, service string) string {
	if service[0] == '/' {
		service = service[1:]
	}

	if prefix[len(prefix)-1] == '/' {
		return prefix + service
	} else {
		return prefix + "/" + service
	}
}

func getNameFromPath(path string) string {
	index := strings.LastIndex(path, "/")
	if index == -1 {
		return ""
	}

	return path[index+1:]
}
